package cn.rui.service;

import cn.rui.mapper.ImgCategoryMapper;
import cn.rui.mapper.ImgMapper;
import cn.rui.pojo.Image;
import cn.rui.pojo.ImageCategory;
import cn.rui.vo.ImageQuery;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 徽州大都督
 * @date 2020/8/16
 */
@Service
public class ImgService {

    @Autowired
    private ImgMapper imgMapper;
    @Autowired
    private ImgCategoryMapper imgCategoryMapper;

    @Value("${server.port}")
    private int port;
    @Value("${server.servlet.context-path}")
    private String path;

    public String uploadImg(MultipartFile file, String statusStr, String category, String descImg) throws IOException {
        BufferedImage read = ImageIO.read (file.getInputStream ());
        int width = read.getWidth (); //宽
        int height = read.getHeight (); //高

        //获取文件的原始名称
        String oldFileName = file.getOriginalFilename ();

        //获取原始名称的后缀
        //String s = oldFileName.split (".")[1];
        //或者使用工具类，引入commons-fileupload包
        String extension = "." + FilenameUtils.getExtension (oldFileName);

        //String fileEnd = FilenameUtils.getExtension(file.getOriginalFilename());

        //生成新的文件名称
        String newFileName = new SimpleDateFormat ("yyyyMMddHHmmss").format (new Date ()) + UUID.randomUUID ().toString ().replace ("-", "") + extension;

        //获取文件大小
        long size = file.getSize ();

        //超出大小
        if (size > 10485680) {
            return "sizeError";
        }


        //获取文件类型
        String type = file.getContentType ();

        //不是图片类型的返回
        if (!type.contains ("image")) {
            return "error";
        }
        //System.out.println (type);

        //根据日期生成文件目录
        String relePath = ResourceUtils.getURL ("classpath:").getPath () + "/static/files";

        String dateFormat = new SimpleDateFormat ("yyyy-MM-dd").format (new Date ());
        String dataDirPath = relePath + "/" + dateFormat;
        java.io.File dateDir = new java.io.File (dataDirPath);

        if (!dateDir.exists ()) {
            dateDir.mkdirs ();
        }

        //图片链接
        String url = "files/" + dateFormat + "/" + newFileName;
        //System.out.println (url);

        //整体链接
        String urlPath = "http://localhost:" + port + path + "/" + url;
        //System.out.println (urlPath);

        //BufferedInputStream in = new BufferedInputStream (file.getInputStream ());
        //字节流转图片对象
        //Image bi=ImageIO.read (in);
        //构建图片流 按照16:9的比例 设置宽高 240*135
        //BufferedImage tag=new BufferedImage(1080,1920,BufferedImage.TYPE_INT_RGB);

        //绘制改变尺寸后的图
        //tag.getGraphics().drawImage(bi, 0, 0, 240, 135, null);

        //输出流
        //BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream (dataDirPath+"//"+newFileName));
        //ImageIO.write(tag, FilenameUtils.getExtension (oldFileName),out);
        //in.close();
        //out.close();

        //System.out.println("图片地址："+dataDirPath+"//"+newFileName);

        //原方式处理文件上传
        file.transferTo (new java.io.File (dateDir, newFileName));

        //将文件信息放入数据库中
        Image image = new Image ();
        QueryWrapper<ImageCategory> wrapper = new QueryWrapper<> ();
        wrapper.eq ("category_name", category);
        ImageCategory imageCategory = imgCategoryMapper.selectOne (wrapper);

        image.setCid (imageCategory.getCid ());
        image.setImgName (newFileName);
        image.setImgUrl (urlPath);

        if (statusStr.equals ("显示")) {
            image.setImgStatus (1);
        } else {
            image.setImgStatus (0);
        }
        image.setDescImg (descImg);
        image.setSizeStr (width + "X" + height);

        imgMapper.insert (image);


        return "success";
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    public List<Image> findByPage(int page, int size, ImageQuery query) {
        Page<Image> page1 = new Page<> (page, size);

        List<ImageCategory> imageCategories = imgCategoryMapper.selectList (null);

        List<Image> list = imgMapper.selectList (null);
        for (ImageCategory category : imageCategories) {
            QueryWrapper<Image> wrapper = new QueryWrapper<> ();
            wrapper.eq ("cid", category.getCid ());
            List<Image> images = imgMapper.selectList (wrapper);
            category.setNum (images.size ());
            category.setSum (list.size ());
        }

        QueryWrapper<Image> wrapper = new QueryWrapper<> ();

        if (query.getCid () != 0) {
            wrapper.eq ("cid", query.getCid ());
        }

        IPage<Image> imageIPage = imgMapper.selectPage (page1, wrapper);
        long total = imageIPage.getTotal ();

        //查询结果为空
        if (total == 0) {
            List<Image> imageList = new ArrayList<> ();
            Image image = new Image ();
            image.setTotal (total);
            image.setCategories (imageCategories);
            imageList.add (image);
            return imageList;
        }

        List<Image> imageList = imageIPage.getRecords ();
        for (Image image : imageList) {
            image.setTotal (total);
            image.setImageCategory (imgCategoryMapper.selectById (image.getCid ()));
            image.setCategories (imageCategories);
        }

        return imageList;
    }

    /**
     * 删除图片
     *
     * @param mid
     */
    public void delImg(Integer mid) {
        imgMapper.deleteById (mid);
    }

    /**
     * 更新图片状态
     *
     * @param mid
     */
    public void updateStatus(Integer mid) {

        Image image = imgMapper.selectById (mid);
        if (image.getImgStatus () == 1) {
            image.setImgStatus (0);
        } else {
            image.setImgStatus (1);
        }

        imgMapper.updateById (image);
    }
}
